/*
扫雷游戏：
初级：10个  9*9
中级：40个  16*16(默认初始化)
高级：99个  16*30
 */
//1.生成一张雷地图
var mineSweepingMap = function (r,c,mine) {
    let map = [];
    // 给行数，生成一个 1 维数组
    var row = function (r) {
        for (var i = 0; i < r; i++) {
            map[i] = new Array()
        }
    }
    // 给列数，生成一个 2 维数组
    var column = function (col) {
        for (var i = 0; i < map.length; i++) {
            for (var j = 0; j < col; j++) {
                map[i][j] = 0
            }
        }
    }
    //给列数和行数生成空地图
    let blankMap = function(r,c){
       row(r);
       column(c);
    }
    //根据地雷数随机填入地雷
    let writeInMine = function(mine){
        let randomLocation = function(){
            let x = Math.floor(Math.random() * r);
            let y = Math.floor(Math.random() * c);
            if(map[x][y]!==9){
                map[x][y] = 9;
            }else{
                randomLocation();
            }
        }
        for(let i=0;i<mine;i++){
            randomLocation();
        }
    }
    //使用循环给雷边上所有数+1，已经是雷除外
    let plus = function(array,x,y){
        if( x>=0 && x<r && y>=0 && y<c){
            if(array[x][y] !== 9){
                array[x][y] += 1;
            }
        }
    }
    let writeInHint = function(){
        for(let x = 0;x<map.length;x++){
            for(let y=0;y<map[0].length;y++){
                if(map[x][y] === 9){
                    //上下6个
                    for(let i=-1;i<2;i++){
                        plus(map,x-1,y+i);
                        plus(map,x+1,y+i);
                    }
                    //左右2个
                    plus(map,x,y-1);
                    plus(map,x,y+1);
                }
            }
        }
    }
    blankMap(r,c);//生成
    writeInMine(mine);
    writeInHint();
    return map;
}
//2.将雷写入页面
var writeHtml = function(map){
    // 先通过 y轴数量写入 ul，然后通过 x轴上的数量写入 li
    let x = document.querySelector(".game");
    for(let i=0;i<map.length;i++){
        x.innerHTML = x.innerHTML + `<ul class="row x-${i}" data-x="${i}"></ul>`
    }
    let z = document.querySelectorAll('.row');
    for(let i=0;i<z.length;i++){
        for(let j=0;j<map[0].length;j++){
            var m = map[i][j];
            if(m===0){
                m = '';
            }
            z[i].innerHTML = z[i].innerHTML + `
                <li class="col y-${j} num-${m}" data-y="${j}">
                    <span>${m}</span>
                    <img src="flag.svg" class="img-flag hide">
                </li>`
        }
    }
}
//3.判断是否胜利
var changeClearMineNum = function(clearMineNum){
    if(clearMineNum == ((row * col)-mine)){
        let all = document.querySelectorAll('.col');
        let allNum = 0;
        let stop = setInterval(function(){
            let r = Math.floor(Math.random() * 256);
            let g = Math.floor(Math.random() * 256);
            let b = 255;
            all[allNum].children[0].style.opacity = `0`;
            all[allNum].children[1].style.opacity = `0`;
            all[allNum].style.background = `rgba(${r},${g},${b},0.6)`;
            allNum++;
            if(allNum === all.length){
                clearInterval(stop);
                if(zz === 0){
                    alert("你成功了！");
                    initializeGame(row,col,mine);
                }
                initializeGame(row,col,mine);
            }
        },20)
    }else if(zz === 1){
        alert('游戏失败！');
        clearInterval(stopTime);
        let all = document.querySelectorAll('.col');
        let ff = [];//用来存储地雷位置
        let allNum = 0;
        //for循环找到所有地雷，然后放进ff数组
        for(let i=0;i<all.length;i++){
            if(all[i].children[0].innerText === '9'){
                ff[allNum] = all[i];
                allNum++;
            }
        }
        allNum = 0;
        let time = 60;
        if(mine > 50){
            time = 10;
        }else if(mine > 10){
            time = 25;
        }
        //慢慢显示所有地雷的位置
        var stop = setInterval(function(){
            ff[allNum].classList.add('boom');
            allNum++;
            if(allNum === ff.length){
                clearInterval(stop);
                initializeGame(row,col,mine);
            }
        },time)
    }
}
//4.扫雷过程
var clearMine = function(row,col,mine){
    var clearMineNum = 0;
    let mineNums = 0;//判断周围的雷数
    let flagNums = 0;//判断周围被标记数量
    let flags = 1;//用来不自动智能扫雷
    //点击某个方块后显示
    var makeWhite = function(x,y){
        if(x>=0 && y>=0 && x<row && y<col){
            let el =document.querySelector(`.x-${x}`).children[y];
            if(el.style.background !== 'white' && flags){
                el.style.background = 'white';
                el.children[0].style.opacity = `1`;
                // el.children[1].classList.add('hide');
                clearMineNum++;
                changeClearMineNum(clearMineNum);
                if(el.innerText == ''){
                    showNoMine(x,y);
                }
            }if(el.innerText === '9' && !flags){
                mineNums++;
            }if(!el.children[1].classList.contains('hide') && !flags){
                flagNums++;
            }
        }
    }
    //智能扫雷,判断周围一圈有没有雷，没有就自动显示
    var showNoMine = function(x,y){
        makeWhite(x-1,y);
        makeWhite(x-1,y+1);
        makeWhite(x-1,y-1);
        makeWhite(x+1,y);
        makeWhite(x+1,y+1);
        makeWhite(x+1,y-1);
        makeWhite(x,y+1);
        makeWhite(x,y-1);
    }
    //给所有方块添加点击事件，点击显示数字or地雷
    var show = function(){
        let x = document.querySelectorAll('.row');
        for(let i=0;i<x.length;i++){
            x[i].addEventListener('click',function(event){
                let el = event.target;
                if(el.tagName != 'LI'){
                    //因为事件委托的原因,点击到span上面,那就会出现bug.
                    //所以如果点击到span上面，el就等于它的父节点
                    el = event.target.parentElement;
                }
                //右键标记的位置不能点击
                let flag = el.children[1].classList.contains('hide');
                if(el.tagName === 'LI' && flag){
                    if(el.children[0].innerText !== '9' && el.style.background !=='white'){
                        el.children[0].style.opacity = '1';
                        el.style.background = 'white';
                        clearMineNum++;
                        changeClearMineNum(clearMineNum);
                    }else if(el.children[0].innerText === '9'){
                        zz = 1;
                        el.classList.add('boom');
                        changeClearMineNum(0);
                    }
                    //如果点击的方格为空（什么有没有），那么周围没有点开的空方格都会被点开
                    if(el.children[0].innerText === ''){
                        //获取位置
                        let x = parseInt(el.parentElement.dataset.x);
                        let y = parseInt(el.dataset.y);
                        //console.log(x,y);
                        showNoMine(x,y);
                    }
                }
            })
        }
        //右键标记事件实现
        for(var i=0;i<x.length;i++){
            var mineNum = mine;
            x[i].addEventListener('contextmenu',function(event){
                event.preventDefault();
                let el = event.target;
                if(el.tagName !== 'LI'){
                    //因为事件委托的原因,点击到span上面,那就会出现bug.
                    //所以如果点击到span上面，el就等于它的父节点
                    el = event.target.parentElement;
                }
                if(el.tagName === 'LI'){
                    let classList = el.children[1].classList;
                    //已经被点击过的地方不能被标记
                    if(classList.contains('hide') && el.style.background!=='white'){
                        let residue = document.querySelector('.residue');
                        if(mineNum !== 0){
                            mineNum --;
                        }
                        //console.log(`${mineNum}`);
                        residue.innerText = `${mineNum}`;
                        classList.remove('hide');
                    }else if(el.style.background !== 'white'){
                        let residue = document.querySelector('.residue');
                        if(mineNum < mine){
                            mineNum++;
                        }
                        residue.innerText = `${mineNum}`;
                        classList.add('hide');
                        console.log(`${mineNum}`);
                    }
                }
            })
        }
    }
    //点击空白地方，如果周围一圈被标记的的雷全部找到，还是剩下未点击的地方直接显示。
    var check = function(){
        let x = document.querySelectorAll('.row');
        for(var i=0;i<x.length;i++){
            x[i].addEventListener('dblclick',function(event){
                let el = event.target;
                if(el.tagName != 'LI'){
                    //因为事件委托的原因,点击到span上面,那就会出现bug.
                    //所以如果点击到span上面，el就等于它的父节点
                    el = event.target.parentElement;
                }
                if(el.tagName === 'LI' && el.style.background ==='white'){
                    //获取位置
                    let x = parseInt(el.parentElement.dataset.x);
                    let y = parseInt(el.dataset.y);
                    flags = 0;
                    showNoMine(x,y);
                    if(flagNums === mineNums){
                        var checks = function(x,y){
                            if(x>=0 && y>=0 && x<row && y<col){
                                let el =document.querySelector(`.x-${x}`).children[y];
                                if(el.style.background !== 'white' && el.children[1].classList.contains('hide')){
                                    if(el.innerText == '9'){
                                        zz = 1;
                                        changeClearMineNum(0);
                                        flags = 1;
                                    }else {
                                        el.style.background = 'white';
                                        el.children[0].style.opacity = `1`;
                                        el.children[1].classList.add('hide');
                                        clearMineNum++;
                                        changeClearMineNum(clearMineNum);
                                    }
                                }
                            }
                        }
                        for(let i=-1;i<2;i++){
                            for(let j=-1;j<2;j++){
                                if(flags){
                                    break;
                                }
                                checks(x+i,y+j);
                            }
                        }
                    }else{
                        flagNums = 0;
                        mineNums = 0;
                    }
                    flags = 1;
                }
            })
        }
    }
    show();
    check();
}
//5.清除页面，然后写入新的页面
var stopTime;
var initializeGame = function(row,col,mine){
    let residue = document.querySelector('.residue');
    residue.innerText = `${mine}`;
    let time = document.querySelector('.tick');
    time.innerText = `0`;
    let i = 1;
    clearInterval(stopTime);
    stopTime = setInterval(function(){
        time.innerText = `${i++}`;
    },1000);
    //zz
    zz = 0;
    //先清除原来的页面，再重新布局
    let box = document.querySelector('.game');
    box.innerHTML = '';
    let map = mineSweepingMap(row,col,mine);
    writeHtml(map);
    clearMine(row,col,mine);
}
//6.选择游戏等级，给按钮绑定功能
var Btn = function(){
    let level = document.getElementsByClassName('choice-level');
    for(let i = 0;i < level.length;i++){
        level[i].addEventListener('click',function(e){
            var level = e.target.innerHTML;
            if(level=="初级"){
                row = 9;
                col = 9;
                mine = 10;
                initializeGame(row,col,mine);
            }else if(level=="中级"){
                row = 16;
                col = 16;
                mine = 40;
                initializeGame(row,col,mine);
            }else if(level=="高级"){
                row = 16;
                col = 30;
                mine = 99;
                initializeGame(row,col,mine);
            }
        })
    }
    let restart = document.querySelector('.restart');
    restart.addEventListener('click',function(e){
        initializeGame(row,col,mine);
    })
}
Btn();
//7.初始数据
//zz 用来确定是否已经点到地雷
var zz = 0;
var row = 16;
var col = 16;
var mine = 40;
initializeGame(row,col,mine);